/*++

Copyright (c) 2007  Microsoft Corporation 

Filename: 

    Global.cs

Abstract: 

    A class to define Common Enums, Properties and Methods
*/

using System;
using System.Collections.Generic;
using System.Text;
using Visio = Microsoft.Office.Interop.Visio;
using System.Reflection;
using System.Resources;
using Microsoft.Win32;
using System.Globalization;

namespace NRTMAddIn
{
    class Global
    {
        #region enum

        /// <summary>
        /// Enum for various options for diagram generation
        /// </summary>
        internal enum InputDataOption
        {
            SCOM,
            Excel,
            ActivePage,
            ActiveShape
        }

        /// <summary>
        /// Fill enums for ShapeSheet values.
        /// </summary>
        internal enum VisioColors
        {
            Black = 0,
            Red = 1,
            Yellow = 2,
            Green = 3,
            Default=4
        }

        /// <summary>
        /// Fill enums for ThreadState.
        /// </summary>
        internal enum ThreadStop
        {
            Abort,
            Cancel,
            Complete
        }

        #endregion

        #region Private Variables

        public const string ApplicationID = "nrtmaddin";
        public const string ApplicationIndex = "nrtmaddinindex";
        public const string ServerMasterName = "Server";
        public const string EthernetMasterName = "Ethernet";

        #region Context Strings
        public const string ApplicationContextString = "/app=";
        public const string DocumentContextString = "/doc=";
        public const string PageContextString = "/page=";
        public const string ShapeContextString = "/shape=";
        public const string ShapeUContextString = "/shapeU=";
        public const string CommandContextString = "/cmd=";
        #endregion

        public const string DocTemplateUserProp = "User.NRTMAvail";

        public static string AddinTemplate = Global.AppPath() + "Graphics\\NRTM_U.vst";
        public static string AddinStencil = "NRTM_DG_U.vss";

        public static string AddinHelpFile = Global.AppPath() + "HelpFile\\User Guide for Visio Add-In for Disk Space Monitoring.pdf";
        #region Menu States
        public const string MenuStateApplicationOpen = "ApplicationOpen";
        public const string MenuStateDocumentOpen = "DocumentOpen";
        public const string MenuStateDiagramCreated = "DiagramCreated";
        public const string MenuStateDiagramCreation = "DiagramCreation";
        public const string MenuStateMonitoringInProgress = "MonitoringInProgress";
        public const string MenuStateMonitoringCompleted = "MonitoringCompleted";
        public const string MenuStateSetStatus = "SetStatusWindow";
        public const string MenuStateResetStatus = "ResetStatusWindow";
        public const string MenuStateSetReport = "SetReportWindow";
        public const string MenuStateResetReport = "ResetReportWindow";
        public const string MenuStateToggleStatus = "ToggleStatus";
        public const string MenuStateToggleReport = "ToggleReport";
        #endregion

        #region Command Strings
        public const string CommandStringHelp = "Help";
        public const string CommandStringAbout = "About";
        public const string CommandStringDrill = "DrillAction";
        public const string CommandStringNRTMOptions = "NRTMOptions";
        public const string CommandStringSelectMachines = "SelectMachines";
        public const string CommandStringCancelDiagram = "CancelDiagram";
        public const string CommandStringStartMonitoring = "StartMonitoring";
        public const string CommandStringStopMonitoring = "StopMonitoring";
        public const string CommandStringShowStatusWindow = "ShowStatusWindow";
        public const string CommandStringShowReportWindow = "ShowReportWindow";
        public const string CommandStringExportReportToExcel = "ExportReportToExcel";
        #endregion

        private static string _excelFileName;
        private static InputDataOption _ipOption = InputDataOption.ActiveShape;
        private static Visio.Application _visioApp;

        #region Database variables
        private static string _ServerName = "";
        #endregion

        #region Options Variables
        private static Int32 _MinValRed;
        private static Int32 _MaxValRed = 15;
        private static Int32 _MinValYellow = 15;
        private static Int32 _MaxValYellow = 60;
        private static Int32 _MinValGreen = 60;
        private static Int32 _MaxValGreen = 100;
        #endregion

        private static ResourceManager resourceMgr = new ResourceManager("NRTMAddIn.GlobalResource", Assembly.GetExecutingAssembly());

        #endregion

        #region Properties        

        public static InputDataOption IPOption
        {
            get
            {
                return _ipOption;
            }
            set
            {
                _ipOption = value;
            }
        }

        public static string ExcelFileName
        {
            get
            {
                return _excelFileName;
            }
            set
            {
                _excelFileName = value;
            }
        }

        public static Visio.Application VisioApp
        {
            get
            {
                return _visioApp;
            }
            set
            {
                _visioApp = value;
            }
        }

        public static string ServerName
        {
            get
            {
                return _ServerName;
            }
            set
            {
                _ServerName = value;
            }
        }
        
        public static Int32 MinValRed
        {
            get
            {
                return _MinValRed;
            }
            set
            {
                _MinValRed = value;
            }
        }

        public static Int32 MaxValRed
        {
            get
            {
                return _MaxValRed;
            }
            set
            {
                _MaxValRed = value;
            }
        }

        public static Int32 MinValYellow
        {
            get
            {
                return _MinValYellow;
            }
            set
            {
                _MinValYellow = value;
            }
        }

        public static Int32 MaxValYellow
        {
            get
            {
                return _MaxValYellow;
            }
            set
            {
                _MaxValYellow = value;
            }
        }

        public static Int32 MinValGreen
        {
            get
            {
                return _MinValGreen;
            }
            set
            {
                _MinValGreen = value;
            }
        }

        public static Int32 MaxValGreen
        {
            get
            {
                return _MaxValGreen;
            }
            set
            {
                _MaxValGreen = value;
            }
        }        

        #endregion

        #region Methods

        /// <summary>
        /// Get resource string from resource file
        /// </summary>
        /// <param name="resKey"></param>
        /// <returns></returns>
        public static string GetResourceString(string resKey)
        {
            try
            {
                return resourceMgr.GetString(resKey);
            }
            catch (Exception ex)
            {
                throw new NrtmException("Error in getting Resource String", ex);
            }
        }

        

        /// <summary>
        /// Convert value to formula string by appending quotes
        /// </summary>
        /// <param name="inputValue"></param>
        /// <returns></returns>
        public static string StringToFormulaForString(string inputValue)
        {

            string result = "";
            string quote = "\"";
            string quoteQuote = "\"\"";

            try
            {

                result = inputValue != null ? inputValue : String.Empty;

                // Replace all (") with ("").
                result = result.Replace(quote, quoteQuote);

                // Add ("") around the whole string.
                result = quote + result + quote;
            }
            catch (Exception err)
            {
                System.Diagnostics.Debug.WriteLine(err.Message);
                throw;
            }

            return result;
        }

        /// <summary>
        /// Get the application installed path
        /// </summary>
        /// <returns></returns>
        static internal string AppPath()
        {
            string appPathFilename = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string directoryName = System.IO.Path.GetDirectoryName(appPathFilename);

            if (!directoryName.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
            {
                directoryName += System.IO.Path.DirectorySeparatorChar.ToString();
            }

            // return result
            return directoryName;
        }

        /// <summary>
        /// Check if MS Excel installed
        /// </summary>
        /// <returns>True if excel is installed</returns>
        internal static bool ExcelInstalled()
        {
            string officeExcelKey2007 = @"SOFTWARE\Microsoft\Office\12.0\Excel";
            string officeExcelKey2003 = @"SOFTWARE\Microsoft\Office\11.0\Excel";

            //Check if excel installed using registry
            RegistryKey regKeyExcel2003 = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,
                System.Environment.MachineName).OpenSubKey(officeExcelKey2003);
            RegistryKey regKeyExcel2007 = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine,
                System.Environment.MachineName).OpenSubKey(officeExcelKey2007);

            if (regKeyExcel2003 == null && regKeyExcel2007 == null)
            {
                return false;
            }

            //Excel installed
            return true;
        }

        /// <summary>
        /// Parse the string and return value part from RHS of = in the string
        /// </summary>
        /// <param name="commandString"></param>
        /// <returns></returns>
        internal static string ParseCommandValue(string commandString)
        {
            return commandString.Substring(commandString.IndexOf("=") + 1);
        }

        /// <summary>
        /// Get the visio objects from the context string
        /// </summary>
        /// <param name="ContextString">Conext String</param>
        /// <param name="visioApplication">Visio Appilcation</param>
        /// <param name="visioDocument">Visio Document</param>
        /// <param name="visioPage">Visio Page</param>
        /// <param name="visioShape">Visio Shape</param>
        /// <param name="appid">Application ID</param>
        /// <param name="cmd">Command Action</param>
        internal static void GetVisioObjects(string ContextString,
            Visio.Application visioApplication,
            ref Visio.Document visioDocument,
            ref Visio.Page visioPage,
            ref Visio.Shape visioShape,
            ref string appid,
            ref string cmd)
        {
            string _appid = null;
            string docid = null;
            string pageid = null;
            string shapeId = null;
            string shapeUId = null;
            string _cmd = null;
            bool isIndex;

            try
            {
                List<string> contextList = new List<string>();
                contextList.AddRange(ContextString.Split(' '));
                contextList.ForEach(
                    delegate(string item)
                    {
                        if (item.Contains(Global.ApplicationContextString))
                        {
                            //Get application id
                            _appid = Global.ParseCommandValue(item);
                        }
                        if (item.Contains(Global.DocumentContextString))
                        {
                            //Get document id
                            docid = Global.ParseCommandValue(item);
                        }
                        if (item.Contains(Global.PageContextString))
                        {
                            //Get page id
                            pageid = Global.ParseCommandValue(item);
                        }
                        if (item.Contains(Global.ShapeContextString))
                        {
                            //Get shape id
                            shapeId = Global.ParseCommandValue(item);
                        }
                        if (item.Contains(Global.ShapeUContextString))
                        {
                            //Get shapeU id
                            shapeUId = Global.ParseCommandValue(item);
                        }
                        if (item.Contains(Global.CommandContextString))
                        {
                            //Get command
                            _cmd = Global.ParseCommandValue(item);
                        }
                    }
                );

                isIndex = false;

                if (_appid == null)
                {
                    //Event not raised for NRTM
                    return;
                }

                if (string.Compare(_appid, Global.ApplicationIndex, true, CultureInfo.CurrentCulture) == 0)
                {
                    //Check if document ID or Index is received in the ContextString
                    //Overwrite the appid to be unique after this point
                    isIndex = true;
                    _appid = Global.ApplicationID;
                }
                appid = _appid;

                if (string.Compare(appid, Global.ApplicationID, true, CultureInfo.CurrentCulture) != 0)
                {
                    return;
                }

                cmd = _cmd;

                if (shapeUId != null)
                {
                    //If shapeU id is not null use it instead of shape id
                    shapeId = shapeUId;
                }

                // get the objects based on the arguments
                if (docid != null &&
                    visioApplication.Documents.Count > 0)
                {
                    if (!isIndex)
                    {
                        //Get document reference from ID
                        visioDocument = visioApplication.Documents.get_ItemFromID(Int32.Parse(docid, System.Globalization.CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        //Get document reference from Index
                        visioDocument = visioApplication.Documents[Int32.Parse(docid, System.Globalization.CultureInfo.InvariantCulture)];
                    }
                }

                if (pageid != null &&
                    visioDocument != null &&
                    visioDocument.Pages.Count > 0)
                {
                    visioPage = visioDocument.Pages[Int32.Parse(pageid, System.Globalization.CultureInfo.InvariantCulture)];
                }

                if (shapeId != null &&
                    visioPage != null &&
                    visioPage.Shapes.Count > 0)
                {
                    visioShape = visioPage.Shapes.get_ItemU(shapeId);
                }
            }
            catch (Exception ex)
            {
                //Throw user-defined exception
                throw new NrtmException("Get Visio Objects", ex);
            }
        }

        /// <summary>
        /// Return disk state based on the free space
        /// </summary>
        /// <param name="freePerc">Free space available</param>
        /// <returns>Disk state</returns>
        internal static string GetDiskState(int freePerc)
        {
            string diskState = string.Empty;

            if (freePerc >= Global.MinValGreen && freePerc <= Global.MaxValGreen)
            {
                diskState = Global.GetResourceString("DiskState_Healthy");
            }
            else if (freePerc >= Global.MinValYellow && freePerc <= Global.MaxValYellow)
            {
                diskState = Global.GetResourceString("DiskState_Normal");
            }
            else if (freePerc >= Global.MinValRed && freePerc <= Global.MaxValRed)
            {
                diskState = Global.GetResourceString("DiskState_Low");
            }

            return diskState;
        }

      #endregion

    }
}
